import React, { useState, useEffect } from 'react'
import { Table, Button, Input, Modal, Form, message, Select, Space, Popconfirm, InputNumber, Dropdown, Tag } from 'antd';
import axios from 'axios';
export default function GoodsManage() {
  const [dataSource, setDataSource] = useState([])
  const [messageApi, contextHolder] = message.useMessage();
  const [open, setOpen] = useState(false);
  const [nowItem, setNowItem] = useState("");
  useEffect(() => {
    axios.get("/goods/selectall").then(res => {
      setDataSource(res.data)
    })
  }, [])
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: "center",
      width: "10%",
      render: (text, record, index) => {
        return <span style={{ fontSize: "12px" }}>{index + 1}</span>
      }
    },
    {
      title: '商品名称',
      dataIndex: 'goodsname',
      key: 'goodsname',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '所属品类',
      dataIndex: 'goodsclass',
      key: 'goodsclass',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '识别码',
      dataIndex: 'goodscode',
      key: 'goodscode',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },

    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      fixed: 'right',
      align: "center",
      render: (text, item) => {
        return <Space>
          <a style={{ fontSize: "12px", color: "#4e9dfd" }} onClick={() => { setOpen(true); setNowItem(item) }}>修改</a>
          <Popconfirm
            title={"删除"}
            description={"确定删除该商品?"}
            okText="确定"
            cancelText="取消"
            onConfirm={() => { deleteGoods(item) }}
          >
            <a style={{ fontSize: "12px", color: "red" }} >{"删除"}</a>
          </Popconfirm>
        </Space>
      }
    }
  ];
  const deleteGoods = (item) => {
    axios.get("/goods/delete?id=" + item.id).then(res => {
      if (res.data > 0) {
        messageApi.open({
          type: 'success',
          content: '删除成功',
        });
        setDataSource(dataSource.filter(res => { return res.id !== item.id }))
      }
    })
  }
  const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
    const [form] = Form.useForm();
    return (
      <Modal
        open={open}
        title={nowItem !== "" ? "修改商品" : "新增商品"}
        okText="确定"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            goodsname: nowItem?.goodsname,
            goodsclass: nowItem?.goodsclass,
            goodscode: nowItem?.goodscode,
          }}
        >
          <Form.Item
            name="goodsname"
            label="商品名称"
            rules={[
              {
                required: true,
                message: '未输入商品名称！',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="goodsclass"
            label="所属品类"
            rules={[
              {
                required: true,
                message: '未输入所属品类！',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="goodscode"
            label="识别码"
            rules={[
              {
                required: true,
                message: '未输入识别码！',
              },
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    );
  };
  const onCreate = (values) => {
    if (nowItem !== "") {
      axios.post("/goods/update", {
        id: nowItem.id,
        ...values
      }).then(res => {
        if (res.data) {
          messageApi.open({
            type: 'success',
            content: '修改成功',
          });
          var nowdata = dataSource
          let targetObject = nowdata.find(obj => obj.id === nowItem.id);
          if (targetObject) {
            targetObject.goodsname = values.goodsname;
            targetObject.goodsclass = values.goodsclass;
            targetObject.goodscode = values.goodscode;
          }
          console.log(nowdata, dataSource);
          setDataSource(nowdata)
          setNowItem("")
        }
      })
    } else {
      axios.post("/goods/insert", values).then(res => {
        if (res.data) {
          messageApi.open({
            type: 'success',
            content: '添加成功',
          });
          setDataSource([...dataSource, res.data])

        }
      })
    }

    setOpen(false);
  };
  return (
    <div>
      <div >
        {contextHolder}
        <div><Button type="primary" onClick={() => { setOpen(true); }}>新增商品分类</Button></div>
        <Table
          columns={columns} dataSource={dataSource} style={{ margin: "5px 0 0 0" }}
          rowKey={(item) => item.id}
          pagination={{}}
          size='small'
        >
        </Table>
      </div>
      <CollectionCreateForm
        open={open}
        onCreate={onCreate}
        onCancel={() => {
          setOpen(false);
          setNowItem("")
        }}
      />
    </div>
  )
}
